const Article = require('../models/Article')
const {pagination} = require('../utils/utils')
const Category = require('../models/Category')
const Comment = require('../models/Comment')
const Like = require('../models/Like')
const Favorite = require('../models/Favorite')
const Follow = require('../models/Follow')

const {uploadURL, serverURL} = require("../config");
// 添加文章
exports.addArticle = async function (req, res, next) {
  let body = req.body
  console.log('body: ', body)
  if(body.cover){
    body.cover=body.cover.replace(uploadURL,'')
  }else{
    body.cover='/img/article-cover.jpg'
  }
  try {
    const article = await Article.create({
      ...body,
      author: req._id,
    })
    // 分类集合文章ids字段更新
    const category = await Category.findOne({_id: body.category})
    category.aids.push(article._id)
    await category.save()
    res.success('文章添加成功')
  } catch (err) {
    next(err)
  }
}
// 获取首页文章列表，分类文章列表
exports.getArticleList = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10
  const categoryId = req.query.categoryId ? req.query.categoryId : ''
  const userId = req.query.userId ?? ''
  const keyword = req.query.keyword ?? ''
  const query = {is_draft: false}
  if (categoryId) {
    query.category = categoryId
  }
  if (userId) {
    query.author = userId
  }
  if(keyword){
    query.title = {$regex: keyword,$options: 'i'}
  }

  try {
    // 调用分页方法
    const paginateResult = await pagination({
      model: Article,
      select: "-comments  -is_draft",
      sort:{date:-1},
      pageNumber,
      pageSize,
      query,
      populate: [
        {
          path: "comments", // 需要填充的评论字段
          select: "content date", // 选择要展示的字段
        },
        {
          path: "author", // 需要填充的评论字段
          select: "nikname", // 选择要展示的字段
        },
        {
          path: "category", // 需要填充的评论字段
          select: "name", // 选择要展示的字段
        },
      ],
      // populate: ['comments', 'category'],
    });
    let data = {list: []};
    paginateResult.list.forEach((item) => {
      const {
        id,
        title,
        cover_img,
        comment_num,
        category,
        author,
        intro,
        hit_num,
        like_num,
      } = item;
      data.list.push({
        id,
        title,
        cover_img,
        comment_num,
        category,
        intro,
        nikname: author.nikname,
        hit_num,
        like_num,
      });
    });
    data.pagination = paginateResult.pagination;
    res.success(data, "文章列表查询成功");
  } catch (err) {
    console.log(err)
    next(err)
  }
}
//  获取随机文章列表
exports.getRandomArticleList = async (req, res, next) => {
  const limit = req.query.limit ? parseInt(req.query.limit) : 10
  try {
    const articles = await Article.aggregate([
      {$match: {is_draft: false}},
      {$sample: {size: limit}},
      // {
      //   $lookup: {
      //     from: "categories",
      //     localField: "category",
      //     foreignField: "_id",
      //     as: "category",
      //   },
      // },
      // {
      //   $lookup: {
      //     from: "users",
      //     localField: "author",
      //     foreignField: "_id",
      //     as: "author",
      //   },
      // },
      {
        $project: {
          title: 1,
          // author: {$arrayElemAt: ["$author.nikname", 0]},
          // intro: {
          //   $substrCP: ["$content", 0, 100] // 使用 $substrCP 并传入代码点数
          // },
        },
      },
    ]);
    res.success(articles, "随机文章列表查询成功");
  } catch (err) {
    console.log(err)
    next(err)
  }
}
// 获取草稿箱
exports.getDraftList = async (req, res, next) => {
  const pageNumber = req.query.pageNumber ? parseInt(req.query.pageNumber) : 1
  const pageSize = req.query.pageSize ? parseInt(req.query.pageSize) : 10
  try {
    let paginateResult = await pagination({
      model: Article,
      select: '-author -comments  -is_draft',
      sort:{date:-1},
      pageNumber,
      pageSize,
      query: {is_draft: true, author: req._id},
    })

    console.log('paginateResult:', paginateResult)

    let data = {list: [],pagination:paginateResult.pagination};
    paginateResult.list.forEach(item=>{
      console.log('item：',item)
      const  {_id,title,cover_img,intro}=item
      data.list.push({id:_id,title,cover_img,intro})
    })
    console.log('data:',data)
    res.success(data, '草稿箱列表查询成功')
  } catch (err) {
    console.log(err)
    next(err)
  }
}
// 获取文章详情
exports.getArticleDetail = async (req, res, next) => {
  const login_user_id = req._id
  const articleId = req.params.id
  try {
    let article = await Article.findByIdAndUpdate(
      articleId,
      { $inc: { hit_num: 1 } },
      { new: true }
    ).populate([
      {
        path: "comments", // 需要填充的评论字段
        select: "content date", // 选择要展示的字段
        populate: {
          path: "uid",
          select: "nikname avatar",
        },
      },
      {
        path: "author", // 需要填充的评论字段
        select: "nikname follow_num avatar", // 选择要展示的字段
      },
      {
        path: "category", // 需要填充的评论字段
        select: "name", // 选择要展示的字段
      },
    ]);
    //操作栏数据
    const left_action = { islike: 0, isfavorite: 0, isfollow: 0 };
    if (login_user_id) {
      const likeExists = await Like.findOne({
        userId: login_user_id,
        articleId,
      });
      const favoriteExists = await Favorite.findOne({
        userId: login_user_id,
        articleId,
      });
      const followExists = await Follow.findOne({
        followerId: login_user_id,
        followeeId: article.author._id,
      });
      if (likeExists) {
        left_action.islike = 1;
      }
      if (favoriteExists) {
        left_action.isfavorite = 1;
      }
      if (followExists) {
        left_action.isfollow = 1;
      }
    }
    if (!article) {
      return res.error(422, "文章不存在");
    }
    if (article.is_draft) {
      return res.error(422, "文章传参数错误！！");
    }
    article = article.toObject();
    if (article && article.comments.length) {
      article.comments.sort((a, b) => {
        // 假设 date 字段是时间戳或者 Date 对象
        // 如果 date 是字符串，需要先转换为 Date 对象
        return new Date(b.date) - new Date(a.date);
      });
      article.comments.forEach((item) => {
        let imgUrl = "";
        if (item.uid.avatar === "/img/avatar.png") {
          imgUrl = serverURL + item.uid.avatar;
        } else {
          imgUrl = uploadURL + item.uid.avatar;
        }
        item.uid.avatar_img = imgUrl;
      });
    }
    if (article.author.avatar === "/img/avatar.png") {
      article.author.avatar_img = serverURL + article.author.avatar;
    } else {
      article.author.avatar_img = uploadURL + article.author.avatar;
    }
    if (article.cover === "/img/article-cover.jpg") {
      article.cover = serverURL + article.cover;
    } else {
      article.cover = uploadURL + article.cover;
    }
    article.left_action = left_action;
    //获取文章作者的文章数
    const articles = await Article.find({ author: article.author._id });
    article.author.articleCount = articles.length;
    //获取文章作者的点赞数
    const totalikesObj = await Article.aggregate([
      {
        $lookup: {
          from: "Users", // 假设User集合存储作者信息
          localField: "author", // 文章中的作者引用字段
          foreignField: "_id", // User集合中的ID字段
          as: "author_info", // 将匹配的作者信息存储在这个字段
        },
      },
      {
        $group: {
          _id: "$author_info._id",
          // 计算点赞总数
          total_likes: { $sum: "$like_num" },
        },
      },
      {
        $project: {
          total_likes: 1, // 包含点赞总数
        },
      },
    ]);
    article.author.total_likes = totalikesObj[0].total_likes;
    res.success(article, "文章详情查询成功");
  } catch (err) {
    console.log('err: ', err)
  }
}
// 获取草稿箱文章详情
exports.getDraftsDetail = async (req, res, next) => {
  const articleId = req.params.id
  try {
    const article = await Article.findById(articleId).populate([
      {
        path: "author", // 需要填充的评论字段
        select: "nikname follow_num avatar", // 选择要展示的字段
      },
      {
        path: "category", // 需要填充的评论字段
        select: "name", // 选择要展示的字段
      },
    ]);
    article.cover=article.cover_img
    if (!article) {
      return res.error(422, '文章不存在')
    }
    if (!article.is_draft) {
      return res.error(422, '文章传参数错误！！')
    }
    if (article.is_draft && (!req._id || req._id.toString() !== article.author._id.toString())) {
      // 权限判断,草稿箱文章只能作者自己查看
      // 执行操作
      return res.error(403, '你没有权限查看该文章')
    }
    res.success(article, '草稿文章详情查询成功')
  } catch (err) {
    console.log('err: ', err)
  }
}
// 更新文章
exports.modifyArticle = async (req, res, next) => {
  const articleId = req.params.id
  const body = req.body
  console.log('body:',body)
  if(body.cover){
    body.cover=body.cover.replace(uploadURL,'')
  }
  try {
    const article = await Article.findByIdAndUpdate(
      articleId,
      {
        ...body,
        author: req._id,
      },
      {new: true}
    )
    res.success(article, '文章更新成功')
  } catch (err) {
    console.log('err: ', err)
  }
}

// 删除文章
exports.deleteArticle = async (req, res, next) => {
  const articleId = req.params.id
  try {
    const article = await Article.findByIdAndDelete(articleId)
    // 分类集合文章ids字段更新
    if (article.category) {
      const category = await Category.findOne({_id: article.category})
      category.aids.splice(category.aids.indexOf(articleId), 1)
      await category.save()
    }
    // 删除关联评论
    await Comment.deleteMany({aid: articleId})
    res.success('文章删除成功')
  } catch (err) {
    console.log('err: ', err)
  }
}
